<template>
  <el-upload
    class="avatar-uploader"
    action="#"
    :show-file-list="false"
    :before-upload="beforeAvatarUpload"
    :http-request="upload"
  >
    <img v-if="value" :src="value" class="avatar" />
    <i v-else class="el-icon-plus avatar-uploader-icon"></i>
    <el-progress v-if="show" :percentage="percent"></el-progress>
  </el-upload>
</template>

<script>
var COS = require("cos-js-sdk-v5");

// SECRETID 和 SECRETKEY请登录 https://console.cloud.tencent.com/cam/capi 进行查看和管理
var cos = new COS({
  SecretId: "AKIDtb4GBpCI7fxyiASTDgsoTrxoNgiTxA6l",
  SecretKey: "QZiaBVYKp31h6F7h03pKYVCckbCWZKp3",
});
export default {
    props:{
        value:{
            type:String,
            
        }
    },
  data() {
    return {
      imageUrl: "",
      percent:0,
      show:false
    };
  },
  created(){
    console.log(this.value);
  },
  methods: {
    
    upload(res) {
      console.log(res);
      this.show=true,
      cos.putObject(
        
        {
          Bucket: "wh-81-1313896973" /* 填入您自己的存储桶，必须字段 */,
          Region: "ap-nanjing" /* 存储桶所在地域，例如ap-beijing，必须字段 */,
          StorageClass: "STANDARD",
          
          Key:res.file.name,
          Body: res.file, // 上传文件对象
          onProgress: (progressData)=> {
            console.log(progressData);
            this.percent = progressData.percent*100
          },
        },
      
       (err, data) =>{
          console.log(err || data);
          console.log(err);
          console.log(data);
          if(data.statusCode===200){
            this.show=false
            this.$emit('input', `https:${data.Location}`);
            
            console.log(`https:${data.Location}`);
            
          }
        }
      );
    },

    beforeAvatarUpload(file) {
      const isPNG = file.type === "image/png";
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isPNG) {
        this.$message.error("上传头像图片只能是 PNG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isPNG && isLt2M;
    },
  },
};
</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>